package edu.cmu.vlis.wassup;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import sun.misc.Signal;

import edu.cmu.vlis.wassup.sender.ShutdownMessageProcessor;

public class CoordinatorResponder implements Runnable{

	protected int _port;
	protected ServerSocket socket;
	protected Socket clientSocket;
	protected PrintWriter out;
	protected  BufferedWriter out1;
	protected String filename = "test";
	protected BufferedReader reader;


	public CoordinatorResponder(int port) {
		this._port = port;
		try {
			this.socket = new ServerSocket(this._port);

			filename = "Log"+port;
			FileWriter f = new FileWriter(filename);
			out1 = new BufferedWriter(f);
			out1.write("In constructor\n");
			out1.flush();
			/*Runtime.getRuntime().addShutdownHook(new
            		ShutdownCoordinatorResponder(clientSocket,socket,out1));*/
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.initialize(); 
	}

	public void initialize(){

		System.out.println("Waiting for coordinator to show up..");
		try {
            this.socket = new ServerSocket(this._port);
			this.clientSocket = this.socket.accept();
			this.out = new PrintWriter(clientSocket.getOutputStream(), true);
			this.reader = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));

			out1.write("Connected with coordinator\n");
			out1.flush();


		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public void shutDown() {
		try {

			out1.write("CalleD\n");
			out1.flush();
			out1.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Signal.raise(new Signal("INT"));
	}
	@Override 
	public void run(){  
		String line;
		while(true){
			try {
				out1.write("CR looping\n");
				out1.flush();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {
				Thread.sleep(1000);
				if(this.clientSocket == null || !clientSocket.isBound() || clientSocket.isClosed() || !clientSocket.isConnected() || clientSocket.isInputShutdown() || clientSocket.isOutputShutdown()){
					out1.write("Connection died at CR.\n");
					out1.flush();
					this.initialize();               
				}

				line = this.reader.readLine(); 

				out1.write("CR rcvd from coordinator: "+line + "\n");
				out1.flush();

				if(line.equals(("ALIVE?"))){
					this.out.println("Yes");
					out1.write("Send a message Yes!\n");
					this.out.flush();

				}             

				else if(line.contains(("Restart:"))){
					this.out.println("No");
					out1.write("Send a message Yes!\n");
					this.out.flush();

				}    
				else {
					this.out.println("");
					this.out.flush();
					out1.write("I am sending empty line.. bec i dont know wht i got.. .\n");
					out1.flush();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			catch (InterruptedException e) {
				try {
					out1.write("connection lost11\n");
					out1.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}catch (NullPointerException npe){
				try {
					out1.write("connection lost\n");
					out1.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				this.initialize();
			}
		}

	}
}
